package com.smart.carts.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.smart.carts.common.exception.ServiceException;
import com.smart.carts.common.reqeust.CartsRequestParams;
import com.smart.carts.common.vo.ResponseCode;
import com.smart.carts.entity.Carts;
import com.smart.carts.mapper.CartMapper;
import com.smart.carts.service.CartService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 *
 */
@Service
public class CartServiceImpl implements CartService {
    @Resource
    CartMapper cartMapper;

    /**
     * 10  布娃娃    10
     *
     * @param cartsRequestParams
     * @return qo对象
     * 转化成
     * po对象  entity
     */
    @Override
    public Boolean add(CartsRequestParams cartsRequestParams) {
        int count;
        try {
            /**
             * 判断用户是否已添加到购物车   用户ID
             */
            Carts carts = cartMapper.selectCartsByMemberId(cartsRequestParams.getMemberId(), cartsRequestParams.getProductId());
            if (carts == null) {
                //添加
                carts = new Carts();
//            Spring BeanUtils
                BeanUtils.copyProperties(cartsRequestParams, carts);
                count = cartMapper.insert(carts);
            } else {
                //  更新的操作   数量的计算  >1
                int quantity = cartsRequestParams.getQuantity() > 1 ? cartsRequestParams.getQuantity() : 1;
                carts.setQuantity(carts.getQuantity() + quantity);
                count = cartMapper.updateById(carts);
            }
        } catch (Exception ex) {
            throw new ServiceException(ResponseCode.SYS_ERROR);
        }
        return count > 0;
    }

    @Transactional(rollbackFor = RuntimeException.class)
    @Override
    public int batchDel(List<Long> ids, Long memberId) {
        int batch = cartMapper.batch(ids, memberId);
        if (batch == ids.size()) {
            return batch;
        } else {
            throw new ServiceException(ResponseCode.ERROR);
        }

    }

    /**
     * 分页查询优化   cartId
     *
     * @param memberId
     * @param page
     * @param size
     * @return
     */
    @Override
    public List<Carts> list(long memberId, int page, int size) {
        PageHelper.startPage(page, size);
        List<Carts> cartsList = cartMapper.selectCartsList(memberId);
        return cartsList;
    }
}
